<template>
  <el-dialog :model-value="dialogVisible" title="通过EXCEL导入人员信息" width="420px" :before-close="handleClose">
    <el-button class="downloadBtn" type="danger" :icon="Download" link @click="_downLoadExcle">下载模板</el-button>
    <el-upload drag :show-file-list="false" :http-request="_uploadFile">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到这里</div>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="tsx" name="UploadDialog">
import { downloadBinaryFile, downloadEvt, getAssetsFile } from "@/utils";
import { ElMessage, UploadRequestOptions } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import { uploadExcle } from "@/api/modules/smartLock/manage/electronMap";

const props = defineProps<{ dialogVisible: boolean; handleClose: () => void }>();

/**
 * 下载导入模板
 */
const _downLoadExcle = () => {
  downloadEvt(getAssetsFile("file/import_room.xlsx"), "import_room.xlsx");
};

/**
 * 文件上传
 */
const _uploadFile = (uploadFileOpts: UploadRequestOptions) => {
  return new Promise<void>(async resolve => {
    const file = uploadFileOpts!.file;
    const site = file.name.lastIndexOf("\.");
    const fileSuffix = file.name.substring(site + 1, file.name.length);

    const fileTypelist = ["xls", "xlsx"];

    if (!fileTypelist.includes(fileSuffix)) {
      ElMessage.error("文件类型不匹配或不支持该种类型文件");
      return false;
    }
    try {
      const res = await uploadExcle({ excel: file });
      downloadBinaryFile(res, "房间导入.xlsx");
      ElMessage.success("导入成功");
    } catch (error) {
      console.log(error);
    }
    props.handleClose();
    resolve();
  });
};
</script>

<style lang="scss" scoped>
.downloadBtn {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
</style>
